package sqlwriter.importation;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import sqlwriter.SQLManager;
import sqlwriter.data.Database;

public class LoadConfig
{
	public static List<Database> run()
	{
		List<Database> listDatabases = new ArrayList<Database>();
		try
		{
			File fXmlFile = new File("SQLWriter/config.xml");
			DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
			DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
			Document doc = dBuilder.parse(fXmlFile);

			doc.getDocumentElement().normalize();

			NodeList nList = doc.getElementsByTagName("database");

			for (int temp = 0; temp < nList.getLength(); temp++)
			{
				Node nNode = nList.item(temp);

				if (nNode.getNodeType() == Node.ELEMENT_NODE)
				{
					Element element = (Element) nNode;
					Database database = new Database();
					database.name = getValue(element, "name");
					database.sqlType = SQLManager.getSQLType(getValue(element, "type"));
					database.namespace = getValue(element, "namespace");
					database.server = getValue(element, "server");
					database.user = getValue(element, "user");
					database.password = getValue(element, "password");

					if (database.name != null && database.sqlType != null)
					{
						listDatabases.add(database);
					}

				}
			}

		}
		catch (Exception e)
		{

		}

		return listDatabases;
	}

	private static String getValue(Element element, String tagName)
	{
		try
		{
			return element.getElementsByTagName(tagName).item(0).getTextContent();
		}
		catch (Exception e)
		{
			return null;
		}

	}
}
